from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.database import get_db
import app.schemas as schemas
from app.services.torrent_service import TorrentService
from app.repositories.config_repository import ConfigRepository

router = APIRouter()

@router.get("/", response_model=List[schemas.Config])
async def get_configs(db: Session = Depends(get_db)):
    """获取所有下载器配置"""
    service = TorrentService(db)
    return await service.get_client_configs()

@router.post("/", response_model=schemas.Config)
async def create_config(config: schemas.ConfigCreate, db: Session = Depends(get_db)):
    """创建新的下载器配置"""
    service = TorrentService(db)
    return await service.add_client_config(config)

@router.put("/{config_id}", response_model=schemas.Config)
async def update_config(config_id: int, config: schemas.ConfigCreate, db: Session = Depends(get_db)):
    """更新配置"""
    repo = ConfigRepository()
    try:
        updated_config = await repo.update_config(db, config_id, config)
        if not updated_config:
            raise HTTPException(status_code=404, detail="配置不存在")
        return updated_config
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/{config_id}/toggle", response_model=schemas.Config)
async def toggle_config(config_id: int, db: Session = Depends(get_db)):
    """切换配置的启用状态"""
    repo = ConfigRepository()
    updated_config = await repo.toggle_config(db, config_id)
    if not updated_config:
        raise HTTPException(status_code=404, detail="配置不存在")
    return updated_config

@router.delete("/{config_id}")
async def delete_config(config_id: int, db: Session = Depends(get_db)):
    """删除下载器配置"""
    service = TorrentService(db)
    success = await service.delete_client_config(config_id)
    if not success:
        raise HTTPException(status_code=404, detail="配置不存在")
    return {"success": True}

@router.post("/test")
async def test_config(config: schemas.ConfigCreate, db: Session = Depends(get_db)):
    """测试下载器连接"""
    service = TorrentService(db)
    result = await service.test_client_connection(config)
    return {"success": result}
